local modname = minetest.get_current_modname()
local S = minetest.get_translator(modname)

if not throwables then return end

if minetest.registered_items['enderpearl:ender_pearl'] then return end

-- Create a throwable enderpearl
local enderpearl = throwables:new(modname .. ":ender_pearl", {
    description = S("Ender Pearl").."\n"..
        S("Left click to throw it@nIt will teleport you on the node it hit making you 2 damage@n(it won't work if you launch it in an unloaded world area)"),
    inventory_image = "enderpearl.png",
    stack_max = 16,
    initial_properties = {
        hp_max = 1,
        physical = true,
        collide_with_objects = false,
        collisionbox = {-0.2, -0.2, -0.2, 0.2, 0.2, 0.2},
        visual = "wielditem",
        visual_size = {x = 0.4, y = 0.4},
        textures = {modname .. ":ender_pearl"},
        spritediv = {x = 1, y = 1},
        initial_sprite_basepos = {x = 0, y = 0},
        pointable = false,
        speed = 56,
        gravity = 32,
        damage = 2,
        lifetime = 10
    },
})


-- Teleport Cooldown
function block_teleport(player, duration)
    if duration then
        minetest.after(duration, function()
            if minetest.get_player_by_name(player:get_player_name()) then
                player:get_meta():set_string("ep_can_teleport", "")
            end
        end)
    end

    player:get_meta():set_string("ep_can_teleport", "false")
end


-- The teleport action
local function teleport_player(self)
    local player = minetest.get_player_by_name(self._player_name)

    if not player then
        self.object:remove()
        return
    elseif player:get_meta():get_string("ep_can_teleport") == "false" then
        self.object:remove()
        return
    end

    player:add_player_velocity(vector.multiply(player:get_player_velocity(), -1))
    player:set_pos(vector.add(self.object:get_pos(), {x = 0, y = 1, z = 0}))
    player:set_hp(player:get_hp() - self.initial_properties.damage, "enderpearl")
    minetest.sound_play("enderpearl_teleport", {max_hear_distance = 10, pos = player:get_pos()})
    block_teleport(player, 0.5)
    self.object:remove()

end


-- Callback functions
local function on_hit_node(self, node)
    teleport_player(self)
end

local function on_hit_entity(self, entity)
    teleport_player(self)
end

local function on_hit_player(self, player)
    teleport_player(self)
end


-- Register callbacks
enderpearl:on_hit_node(on_hit_node)
enderpearl:on_hit_entity(on_hit_entity)
enderpearl:on_hit_player(on_hit_player)
